package com.xiaoliang.servlet.cart;

import com.xiaoliang.entry.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author XIAOLIANG
 * @ClassName UpdateCartProductCount.java
 * @Description TODO
 * @createTime 2021年02月26日 19:04:00
 */
//@WebServlet("/cart/UpdateCount")
public class UpdateCartProductCount extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String type = req.getParameter("type");

		Integer id = Integer.valueOf(req.getParameter("id"));

		HttpSession session = req.getSession();

		HashMap<Integer, Product> cart = (HashMap<Integer, Product>) session.getAttribute("cart");

		if (cart.containsKey(id)){
			Product product = cart.get(id);
			int account = product.getAccount();
			if ("reduce".equals(type)){  //减少的操作
				if (account==1){
					session.setAttribute("msg","数量为1 不能再减少");
				}else {
					product.setAccount(account-1);
					session.setAttribute("cart",cart);  //更新数据
				}

			}else {
				product.setAccount(account+1);
			}


		}else {

			session.setAttribute("msg","修该数量失败,该商品已经不再购物车中!");

		}

		resp.sendRedirect(req.getContextPath()+"/cart/cartList.jsp");

	}
}
